package com.yegs.jltqc.serviceImpl;

import com.yegs.jltqc.TO.NamePageQuery;
import com.yegs.jltqc.VO.BaseUser;
import com.yegs.jltqc.VO.OutCome;
import com.yegs.jltqc.VO.OutCome;
import com.yegs.jltqc.config.ConcurentCache;
import com.yegs.jltqc.dao.OutComeRepository;
import com.yegs.jltqc.service.OutComeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class OutComeServiceImpl implements OutComeService {

    @Autowired
    private OutComeRepository outComeRepository;

    @Override
    public OutCome save(OutCome outCome) {
        outCome.setCreateTime(new Date());
        outCome.setCreateBy( ConcurentCache.getUserName());
        return outComeRepository.save(outCome);
    }

    @Override
    public List<OutCome> list() {
        return outComeRepository.findAll();
    }

    @Override
    public OutCome get(Long id) {
        return outComeRepository.getOne(id);
    }

    @Override
    public void del(Long id) {
        outComeRepository.deleteById(id);
    }

    @Override
    public Page<OutCome> query(NamePageQuery query) {
        PageRequest request = PageRequest.of(query.getPageIndex() - 1, query.getPageSize());
        if(query.getName() == null || query.getName().trim() == ""){
            return outComeRepository.findAll(request);
        }
        return outComeRepository.findOutComeByName(query.getName(), request);
    }

    @Override
    public Long getNext(Long id) {
        if(id == null){
            OutCome outCome = outComeRepository.findFirstByOrderByIdDesc();
            if(outCome != null) {
                return outCome.getId();
            }
        }
        OutCome outCome = outComeRepository.findFirstByIdIsAfter(id);
        if(outCome == null){ outCome = outComeRepository.findFirstByOrderByIdDesc(); }
        if(outCome != null){
            return outCome.getId();
        }
        return null;
    }

    @Override
    public Long getLast(Long id) {
        if(id == null){
            OutCome outCome = outComeRepository.findFirstByOrderByIdDesc();
            if(outCome != null) {
                return outCome.getId();
            }
        }
        else{
            OutCome outCome = outComeRepository.findFirstByIdBeforeOrderByIdDesc(id);
            if(outCome == null){ outCome = outComeRepository.findFirstByOrderById(); }
            if(outCome != null){
                return outCome.getId();
            }
        }
        return null;
    }
}
